import { message } from 'ant-design-vue';
import axios from 'axios';
import router from '/@/router';
import { globalData } from '/@/setting/global';

axios.defaults.headers['Content-Type'] = 'application/json';
axios.defaults.withCredentials = true;

let config = {
  baseURL: globalData.apiUrl,
  timeout: 5 * 60 * 1000,
  withCredentials: true,
  Headers: {
    'Content-Type': 'application/json'
  },
};

const http = axios.create(config);

http.interceptors.request.use(
  (config) => {
    const token = sessionStorage.getItem('TOKEN');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
      config.headers['Content-Type'] = 'application/json';
    }
    return config;
  },
  (error) => {
    // Do something with request error
    return Promise.reject(error);
  },
);

// Add a response interceptor
http.interceptors.response.use(
  (response) => {
    // Do something with response data
    return response.data;
  },
  (error) => {
    if (error.message.includes('timeout')) {
      message.error('任务执行时间过长');
    } else if (error.response?.status === 401) {
      router.push('/login');
    }
    // Do something with response error
    return Promise.reject(error.response);
  },
);

export default http;
